/*-
 * SMSEntryUtils.java
 *
 * $LastChangedBy:  $
 * $LastChangedRevision:  $
 * $LastChangedDate:  $
 * $HeadURL: $
 *
 * Copyright (c) 2008, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.intention.tools;

import static com.googlecode.attention.sms.pdu.UDIE.CONCATENATED_SHORT_MESSAGE_16_BIT;
import static com.googlecode.attention.sms.pdu.UDIE.CONCATENATED_SHORT_MESSAGE_8_BIT;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.googlecode.attention.SMSEntry;
import com.googlecode.attention.sms.pdu.ConcatenatedMessage;
import com.googlecode.attention.sms.pdu.MTI;
import com.googlecode.attention.sms.pdu.PDUElement;
import com.googlecode.attention.sms.pdu.TPDU;
import com.googlecode.attention.sms.pdu.UDH;
import com.googlecode.attention.sms.pdu.UDIE;



public class SMSEntryUtils {
  public static TPDU[] convertSMSEntryToTPDU(final SMSEntry[] entries,
                                             final boolean hasSMSCInfo) {
    final int length = entries.length;
    final TPDU[] tpdus = new TPDU[length];
    for (int i = 0; i < length; i++) {
      final SMSEntry entry = entries[i];
      final String pdu = entry.getPDU();      
      final MTI.DIRECTION direction;
      switch (entry.getStatus()) {
      case STORED_SENT_MESSAGES: // submit
      case STORED_UNSENT_MESSAGES:
        direction = MTI.DIRECTION.MS_TO_SC;
        break;

      case RECEIVED_UNREAD_MESSAGES: // deliver unread
      case RECEIVED_READ_MESSAGES: // deliver read
      default:
        direction = MTI.DIRECTION.SC_TO_MS;
        break;
      }
      
      tpdus[i] = TPDU.getPDU(pdu, direction, false, hasSMSCInfo);
    }
    
    return tpdus;
  }
  
  
  public static SMSEntry[] removeDuplicates(final SMSEntry[] entries) {
    final ArrayList<SMSEntry> uniqueEntries
      = new ArrayList<SMSEntry>(entries.length);
    
    for (final SMSEntry entry : entries) {
      if (!uniqueEntries.contains(entry)) uniqueEntries.add(entry); 
    }
    
    return uniqueEntries.toArray(new SMSEntry[uniqueEntries.size()]);
  }
  
  
  public static void printMessages(final SMSEntry[] entries,
                                   final Phonebook phonebook,
                                   final boolean hasSMSCInfo,
                                   final String printPattern,
                                   final String separator,
                                   final PrintStream out) {
    final TPDU[] tpdus = SMSEntryUtils.convertSMSEntryToTPDU(entries, hasSMSCInfo);
    final Map<String, ConcatenatedMessage> concatMap
        = new HashMap<String, ConcatenatedMessage>();
    
    Arrays.sort(tpdus);
    
    final SMSFormatter smsFormatter = new SMSFormatter();
    smsFormatter.setPhonebook(phonebook);
    
    for (final TPDU tpdu : tpdus) {
      tpdu.decode();
      
      if (tpdu.get(PDUElement.TP_UDHI) != 0) {
        ConcatenatedMessage concat = parseUDH(tpdu, concatMap);
        /* concat is null if UDH and not concatenated message */
        if (concat != null && !concat.hasAllParts()) {
          continue;
        }
        out.println(smsFormatter.format(printPattern, concat, separator));
      } else {
        out.println(smsFormatter.format(printPattern, tpdu, separator));
      }
    }
  }
  
  public static ConcatenatedMessage parseUDH(final TPDU sms,
      final Map<String, ConcatenatedMessage> concatMap) {
    final String number = sms.getAddress().getNumber();
    ConcatenatedMessage concat = null;
    final UDH header = sms.getUserDataHeader();
    final UDIE[] elements = header.getInformationElements();
    for (final UDIE element : elements) {
      switch (element.getIdentifier()) {
      case CONCATENATED_SHORT_MESSAGE_8_BIT:
      case CONCATENATED_SHORT_MESSAGE_16_BIT:
        final int[] elementData = element.getData();
        if (elementData.length >= 3) {
          final int ref = elementData[2];
          final int max = elementData[3];
          final int num = elementData[4];

          /* 
           * If the value of the maximum number or the sequence number is
           * zero then the receiving entity shall ignore the whole
           * Information Element.
           * Ref. "3GPP TS 23.040 version 5.8.1 Release 5" page 69.
           */
          if (max == 0 || num == 0) continue;
          
          final String key = number + ":" + ref;
          concat = concatMap.get(key);
          if (concat == null) {
            concat = new ConcatenatedMessage(sms, ref, max, num);
            concatMap.put(key, concat);
          } else {
            concat.addConcat(sms, num);
          }
        }
        break;
        
      default:
        // all other headers ignored
      }
    }
    return concat;
  }
}
